/**
 * 是否为空。
 */
export function empty(v){
  switch (typeof v){
    case 'undefined' : return true;
    case 'string' : if(v.trim().length === 0) return true; break;
    case 'boolean' : if(!v) return true; break;
    case 'number' : if(0 === v) return true; break;
    case 'object' :
      if(null === v) return true;
      if(undefined !== v.length && v.length===0) return true;
      for(let k in v){return false;} return true;
      break;
  }
  return false;
}

/**
 * 加法运算，避免数据相减小数点后产生多位数和计算精度损失。
 *
 * @param num1被减数 | num2减数
 */
export function numSub(num1, num2) {
  let baseNum;
  let baseNum1;
  let baseNum2;
  let precision; // 精度
  try {
    baseNum1 = num1.toString().split('.')[1].length;
  } catch (e) {
    baseNum1 = 0;
  }
  try {
    baseNum2 = num2.toString().split('.')[1].length;
  } catch (e) {
    baseNum2 = 0;
  }
  baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
  precision = baseNum1 >= baseNum2 ? baseNum1 : baseNum2;
  return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
}

/**
 * 乘法运算，避免数据相乘小数点后产生多位数和计算精度损失。
 *
 * @param num1被乘数 | num2乘数
 */
export function numMulti(num1, num2) {
  let baseNum = 0;
  try {
    baseNum += num1.toString().split('.')[1].length;
  } catch (e) {}
  try {
    baseNum += num2.toString().split('.')[1].length;
  } catch (e) {}
  return (
    (Number(num1.toString().replace('.', '')) * Number(num2.toString().replace('.', ''))) /
    Math.pow(10, baseNum)
  );
}
/**
 * 除法运算，避免数据相除小数点后产生多位数和计算精度损失。
 *
 * @param num1被除数 | num2除数
 */
export function numDiv(num1, num2) {
  let baseNum1 = 0;
  let baseNum2 = 0;
  let baseNum3;
  let baseNum4;
  try {
    baseNum1 = num1.toString().split('.')[1].length;
  } catch (e) {
    baseNum1 = 0;
  }
  try {
    baseNum2 = num2.toString().split('.')[1].length;
  } catch (e) {
    baseNum2 = 0;
  }
  baseNum3 = Number(num1.toString().replace('.', ''));
  baseNum4 = Number(num2.toString().replace('.', ''));
  return (baseNum3 / baseNum4) * Math.pow(10, baseNum2 - baseNum1);
}

/**
 *  Describe:9999999 to '9,999,999'
 *  Created by xjc on 2019/6/6
 */

export function NumberDivide(str, fix, strAdd) {
  // number, 保留尾数, 添加符号
  if (str === 'NaN' || typeof str === 'undefined' || str === null || isNaN(str)) {
    return null;
  }
  if (strAdd === 'NaN' || typeof strAdd === 'undefined' || strAdd === null) {
    strAdd = '';
  }
  if (typeof str === 'number') {
    if (typeof fix === 'number') {
      str = str.toFixed(fix);
    } else {
      str = parseFloat(str).toString();
    }
  }
  let a;
  let b;
  let c;
  let d;
  const re = /(?=(?!\b)(\d{3})+$)/g;
  a = str.split('.');
  b = a[0];
  c = b.replace(re, ',');
  d = typeof a[1] === 'string' ? `. ${a[1]}` : '';
  if (strAdd === '$') {
    return strAdd + c + d;
  }
  return c + d + strAdd;
}

/**
 *  Describe:补零
 *  Created by xjc on 2019/6/6
 */

export function FormatnumberZero(value, num) {
  // number or string , 保留位数
  let a;
  let b;
  let c;
  let i;
  a = value.toString();
  b = a.indexOf('.');
  c = a.length;
  if (num === 0) {
    if (b !== -1) {
      a = a.substring(0, b);
    }
  } else {
    // 如果没有小数点
    if (b === -1) {
      a += '.';
      for (i = 1; i <= num; i++) {
        a += '0';
      }
    } else {
      // 有小数点，超出位数自动截取，否则补0
      a = a.substring(0, b + num + 1);
      for (i = c; i <= b + num; i++) {
        a += '0';
      }
    }
  }
  return a;
}

/**
 *  Describe:到现在剩余几天
 *  Created by xjc on 2019/6/6
 */

export function DateDiff(sDate) {
  // sDate日期
  let oDate1;
  let oDate2;
  let iDays;
  oDate1 = new Date(); // 当前日期
  oDate2 = new Date(sDate);
  iDays = parseInt(Math.abs(oDate1 - oDate2) / 950 / 60 / 60 / 24); // 把相差的毫秒数转换为天数
  return iDays; // 返回相差天数
}

/**
 *  Describe:转换时间
 *  Created by xjc on 2019/6/6
 */

export function DateString(date) {
  // sDate日期
  const now = new Date(date);
  const y = now.getFullYear();
  const m = now.getMonth() + 1;
  const d = now.getDate();
  const h = now.getHours();
  const i = now.getMinutes();
  const s = now.getSeconds();
  return `${y}-${m < 10 ? `0${m}` : m}-${d < 10 ? `0${d}` : d} ${h}:${i}:${s}`;
}

/**
 *  Describe:可拖动组件封装（可用于PC antdtable）
 *  Created by xjc on 2019/6/6
 */

export function Mover(title) {
  // 对应dom节点
  this.obj = title;
  this.startx = 0;
  this.starty;
  this.startLeft;
  this.startTop;
  this.mainDiv = title;
  const that = this;
  this.isDown = false;
  this.movedown = function(e) {
    e = e || window.event;
    if (!window.captureEvents) {
      this.setCapture();
    }
    that.isDown = true;
    that.startx = e.clientX;
    that.starty = e.clientY;

    that.startLeft = parseInt(that.mainDiv.scrollLeft);
  };
  this.move = function(e) {
    e = e || window.event;
    if (that.isDown) {
      that.mainDiv.scrollLeft = that.startx - e.clientX + that.startLeft;
      /* if(e.clientX!==that.startx){
        console.log(e.clientX+'aaaaaaaaaaaa'+that.startx+'aaaaaaaaaaaa'+that.mainDiv.scrollLeft);
      } */
    }
  };
  this.moveup = function() {
    that.isDown = false;
    if (!window.captureEvents) {
      this.releaseCapture();
    } // 事件捕获仅支持ie
  };
  this.obj.onmousedown = this.movedown;
  this.obj.onmousemove = this.move;
  this.obj.onmouseup = this.moveup;

  // 非ie浏览器
  document.addEventListener('mousemove', this.move, true);
}

/**
 *  Describe: 一级数组转换为树状数组
 *  Created by xjc on 2019/6/6
 */

export function ToTreeDataTable(data) {
  // 父子有对应id和parentid的数组
  const pos = {};
  const tree = [];
  let i = 0;
  while (data.length !== 0) {
    if (data[i].parentid === 0) {
      tree.push({
        children: [],
        ...data[i],
      });
      pos[data[i].id] = [tree.length - 1];
      data.splice(i, 1);
      i--;
    } else {
      const posArr = pos[data[i].parentid];
      if (posArr !== undefined) {
        let obj = tree[posArr[0]];
        for (let j = 1; j < posArr.length; j++) {
          obj = obj.children[posArr[j]];
        }

        obj.children.push({
          children: [],
          ...data[i],
        });
        pos[data[i].id] = posArr.concat([obj.children.length - 1]);
        data.splice(i, 1);
        i--;
      }
    }
    i++;
    if (i > data.length - 1) {
      i = 0;
    }
  }
  function getSelectedNode(nodeData, parent) {
    nodeData.forEach(item => {
      if ('children' in item && item.children.length === 0) {
        delete item.children;
      } else if ('children' in item && item.children.length) {
        getSelectedNode(item.children, item);
      }
    });
  }
  getSelectedNode(tree, tree);
  return tree;
}

/**
 *  Describe:时间戳转换年月日
 *  Created by xjc on 2019/6/11
 */

export function GetDateThree(s) {
  const now = new Date(s);
  const y = now.getFullYear();
  const m = now.getMonth() + 1;
  const d = now.getDate();
  return `${y}-${m < 10 ? `0${m}` : m}-${d < 10 ? `0${d}` : d}`;
}
export function GetDateThreeExcel(numb, format) {
  // 有毒
  const time = new Date((numb - 1) * 24 * 3600000 + 1);
  time.setYear(time.getFullYear() - 70);
  const year = `${time.getFullYear()}`;
  const month = `${time.getMonth() + 1}`;
  const date = `${time.getDate()}`;
  if (format && format.length === 1) {
    return year + format + month + format + date;
  }
  return year + (month < 10 ? `0${month}` : month) + (date < 10 ? `0${date}` : date);
}

/**
 *  Describe:字符串转日期
 *  Created by xjc on 2019/6/13
 */

export function StrToDate(str) {
  // （日月年）
  str = str.trim().replace(/[^\d\.]/g, '');
  const dateStrs = str.split('.');
  const year = parseInt(dateStrs[2], 10);
  const month = parseInt(dateStrs[1], 10) - 1;
  const day = parseInt(dateStrs[0], 10);
  const date = new Date(year, month, day);
  return date;
}

/**
 *  Describe:切空格
 *  Created by xjc on 2019/7/4
 */

export function DateStamp(param) {
  // sDate1和sDate2是yyyy-MM-dd格式
  if (typeof param === 'string') {
    const str = param.replace(/-/g, '/');
    const date = new Date(str);
    return date.getTime();
  }
  return 0;
}

/**
 *  Describe:深拷贝
 *  Created by xjc on 2019/6/11
 */

/* export function DeepClone(obj) {
  //判断拷贝的要进行深拷贝的是数组还是对象，是数组的话进行数组拷贝，对象的话进行对象拷贝
  let objClone = Array.isArray(obj) ? [] : {};
  //进行深拷贝的不能为空，并且是对象或者是
  if (obj && typeof obj === "object") {
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] && typeof obj[key] === "object") {
          objClone[key] = deepClone1(obj[key]);
        } else {
          objClone[key] = obj[key];
        }
      }
    }
  }
  return objClone;
} */

/**
 *  Describe:判断是不是数组
 *  Created by xjc on 2019/8/22
 */

export function isArray(o) {
  return Object.prototype.toString.call(o) == '[object Array]';
}
/**
 *  Describe:HH-MM-dd
 *  Created by xjc on 2019/8/22
 */

export function getNowFormatDate(date) {
  if (date === null) {
    return null;
  }
  const seperator1 = '-';
  const year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = `0${month}`;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = `0${strDate}`;
  }
  const currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}
